<template>
  <div class="page-wrap">
    <div class="page-content" :style="{ height: contentHei }">
      <div class="img-header" style="display: flex;justify-content: space-between">
        <div style="font-weight: 700;font-size: 18px">{{ pageTitle }}</div>
      </div>
      <Divider />
      <div class="table-wrap">
        <div style="display: flex;justify-content: flex-start;align-items: center">
          <div
            style="height: 7px;width: 7px;background-color: #333;border-radius: 50%;margin-right: 10px"
          ></div>
          <div style="font-weight: bold;font-size: 16px">基础信息</div>
        </div>
        <div style="display: flex;justify-content: flex-start;margin-top: 30px;padding-left: 65px">
          <div style="margin-right: 11px">头像：</div>
          <div>
            <Avatar v-show="!showDefaultAvatar" :src="avatar" @on-error="setDefAvatar" style="width:100px;height:100px;border-radius: 10px"/>
            <Avatar v-show="showDefaultAvatar" size="large" style="width:100px;height:100px;border-radius: 10px;background: #468dff;">{{nickname.slice(0,1).toUpperCase()}}</Avatar>
            <!-- <img :src="avatar" style="width:100px;height:100px;border-radius: 10px" /> -->
            <div style="font-size: 12px;color: #666;margin: 20px 0 15px 0">
              建议长宽1:1，不小于100px，JPG、PNG、GIF格式，小于300KB。
            </div>
            <div style="display: flex;justify-content: flex-start">
              <Upload
                :action="upLoadUrl"
                :headers="setUpLoadHead"
                :show-upload-list="false"
                :on-progress="upLoadProgress"
                :before-upload="beforeUpload"
                :on-exceeded-size="onExceededSize"
                :format="['jpg', 'png', 'gif']"
                :on-format-error="onFormatError"
                :on-success="upLoadSuccess"
                :on-error="upLoadErr"
              >
                <Button icon="md-add" type="dashed">图片</Button>
              </Upload>
              <!-- <WarningTip content="请上传jpg，png，gif格式图片,文件大小不能超过300KB"></WarningTip> -->
              <Progress
                v-show="showProgress"
                :percent="progressPercent"
                status="active"
                style="width: 300px;margin-left: 15px"
              />
            </div>
          </div>
        </div>
        <div class="base-style">
          <div style="margin-right: 11px">昵称：</div>
          <div>
            <Input v-model.trim="nickname" placeholder="昵称" style="width: 230px" :readonly="true">
              <Icon
                style="cursor: pointer"
                type="ios-create-outline"
                slot="suffix"
                @click="reverseNikeName"
              />
            </Input>
          </div>
        </div>
        <div class="base-style">
          <div style="margin-right: 11px">邮箱：</div>
          <div>
            <Input v-model.trim="email" placeholder="邮箱" style="width: 230px" :readonly="true">
              <Icon
                style="cursor: pointer"
                type="ios-create-outline"
                slot="suffix"
                @click="reverseEmail"
              />
            </Input>
          </div>
        </div>
        <div class="base-style-phone">
          <div style="margin-right: 11px">手机号：</div>
          <div>
            <Input v-model.trim="mobile" placeholder="手机号" style="width: 230px" :readonly="true">
              <Icon
                style="cursor: pointer"
                type="ios-create-outline"
                slot="suffix"
                @click="reversePhone"
              />
            </Input>
          </div>
        </div>
        <div style="display: flex;justify-content: flex-start;align-items: center;margin-top: 35px">
          <div
            style="height: 7px;width: 7px;background-color: #333;border-radius: 50%;margin-right: 10px"
          ></div>
          <div style="font-weight: bold;font-size: 16px">修改密码</div>
        </div>
        <Form
          ref="formCustom"
          :model="formCustom"
          :rules="ruleCustom"
          :label-width="120"
          style="width: 550px;margin-top: 15px"
        >
          <FormItem label="原密码：" prop="oldPasswd">
            <Input
              style="width:230px"
              :type="pass.oldPassType"
              v-model.trim="formCustom.oldPasswd"
              autoComplete="off"
              placeholder="原密码"
            >
            <div slot="suffix" @click="setPassType('oldPassType')" class="pointer">
              <Icon type="ios-eye-outline" v-if="pass.oldPassType === 'text'" />
              <Icon type="ios-eye-off-outline" v-else />
            </div>
          </Input>
          </FormItem>
          <FormItem label="新密码：" prop="passwd">
            <Input
              style="width:230px"
              :type="pass.passType"
              v-model.trim="formCustom.passwd"
              placeholder="新密码"
              autocomplete="new-password"
            >
            <div slot="suffix" @click="setPassType('passType')" class="pointer">
              <Icon type="ios-eye-outline" v-if="pass.passType === 'text'" />
              <Icon type="ios-eye-off-outline" v-else />
            </div>
          </Input>
          </FormItem>
          <FormItem label="确认密码：" prop="passwdCheck" autocomplete="off">
            <Input
              style="width:230px"
              :type="pass.checkPassType"
              v-model.trim="formCustom.passwdCheck"
              placeholder="确认密码"
              autocomplete="new-password"
            >
            <div slot="suffix" @click="setPassType('checkPassType')" class="pointer">
              <Icon type="ios-eye-outline" v-if="pass.checkPassType === 'text'" />
              <Icon type="ios-eye-off-outline" v-else />
            </div>
          </Input>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSubmit('formCustom')">确定</Button>
            <Button @click="handleReset('formCustom')" style="margin-left: 8px">重置</Button>
          </FormItem>
        </Form>
      </div>
    </div>

    <!--修改昵称-->
    <Modal
      v-model="modalNickName"
      width="500"
      :loading="loadingNickName"
      :mask-closable="false"
      :footer-hide="true"
      title="修改昵称"
    >
      <Form ref="nickNameForm" :model="nickNameForm" :rules="ruleNickName" :label-width="120">
        <FormItem label="新昵称" prop="newName">
          <Input
            v-model.trim="nickNameForm.newName"
            :maxlength="32"
            placeholder="昵称最大长度为32个字符"
          ></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSubmitNickname('nickNameForm')">确定</Button>
          <Button @click="handleResetNickname('nickNameForm')" style="margin-left: 8px"
            >重置</Button
          >
        </FormItem>
      </Form>
    </Modal>
    <!--修改邮箱-->
    <Modal
      v-model="modalEmail"
      width="500"
      :loading="loadingEmail"
      :mask-closable="false"
      :footer-hide="true"
      title="修改邮箱"
    >
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120">
        <FormItem label="新邮箱" prop="email">
          <Input v-model.trim="formValidate.email" placeholder="请填写邮箱地址"></Input>
        </FormItem>
        <FormItem label="验证码" prop="code">
          <Input
            v-model.trim="formValidate.code"
            placeholder="请输入验证码"
            style="width: 150px"
          ></Input>
          <Button type="info" @click="verCodeBtn" :disabled="isDisabled">{{ emailValBtn }}</Button>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSubmitEmail('formValidate')">确定</Button>
          <Button @click="handleResetEmail('formValidate')" style="margin-left: 8px">重置</Button>
        </FormItem>
      </Form>
    </Modal>
    <!--修改手机号-->
    <Modal
      v-model="modalPhone"
      width="500"
      :loading="loadingPhone"
      :mask-closable="false"
      :footer-hide="true"
      title="修改手机号"
    >
      <Form ref="phoneForm" :model="phoneForm" :rules="rulePhoneForm" :label-width="120">
        <FormItem label="新手机号" prop="mobile">
          <Input v-model.trim="phoneForm.mobile" placeholder="请填写手机号"></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSubmitPhone('phoneForm')">确定</Button>
          <Button @click="handleResetPhone('phoneForm')" style="margin-left: 8px">重置</Button>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import $ from 'jquery';
import cookieUse from '@/libs/cookie.js';
import encryption from '@/libs/encryption.js';
import { baseInfo, logout } from '@/api/login.js';
import {
  modifyNickname,
  sendCode,
  modifyEmail,
  modifyPhone,
  modifyPwd,
  modifyAva
} from '@/api/user.js';
import { getPwdBlackList } from '@/api/company.js';
import store from "../../store";
export default {
  components: {},
  data() {
    let regPasswd = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}$/; // 密码必须包含大小写字母、数字和特殊字符，长度为8-16
    const validatePass = (rule, value, callback) => {
      if (regPasswd.test(value)) {
        callback();
      } else {
        callback(new Error('密码必须包含大写字母，小写字母，数字和特殊字符，长度为8-16位'));
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'));
      } else if (value !== this.formCustom.passwd) {
        callback(new Error('两次输入的密码不一致!'));
      } else {
        callback();
      }
    };
    const validateMobile = (rule, value, callback) => {
      let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (value) {
        if (!myreg.test(value)) {
          callback(new Error('请填写正确的手机号'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      // 用户信息
      USER_ID: '',
      isRootDesigner: '',
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: 'auto',
      // 数据
      avatar: '',
      nickname: '',
      email: '',
      mobile: '',
      // 上传头像
      upLoadUrl: `${this.baseURL}/minio/upload?bucket=photo`,
      setUpLoadHead: { Authorization: cookieUse.getCookie('desig-token') },
      showProgress: false,
      progressPercent: 0,
      // 修改昵称
      modalNickName: false,
      loadingNickName: false,
      nickNameForm: {
        newName: ''
      },
      ruleNickName: {
        newName: [{ required: true, message: '昵称不能为空', trigger: 'change' }]
      },
      // 邮箱验证
      emailValBtn: '获取验证码',
      formValidate: {
        email: '',
        code: ''
      },
      ruleValidate: {
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'change' },
          { type: 'email', message: '请输入正确的邮箱', trigger: 'change' }
        ],
        code: [{ required: true, message: '验证码不能为空', trigger: 'change' }]
      },
      isDisabled: false,
      modalEmail: false,
      loadingEmail: true,
      // 修改手机号
      modalPhone: false,
      loadingPhone: false,
      phoneForm: {
        mobile: ''
      },
      rulePhoneForm: {
        mobile: [
          { required: true, message: '手机不能为空', trigger: 'change' },
          { validator: validateMobile, message: '请输入正确的手机号', trigger: 'change' }
        ]
      },
      // 修改密码
      formCustom: {
        oldPasswd: '',
        passwd: '',
        passwdCheck: ''
      },
      ruleCustom: {
        oldPasswd: [{ required: true, message: '原密码不能为空', trigger: 'change' }],
        passwd: [
          { required: true, validator: validatePass, trigger: 'change' },
          {
            type: 'string',
            min: 8,
            max: 16,
            message: '密码必须包含大小写字母、数字和特殊字符，长度为8-16位',
            trigger: 'change'
          }
        ],
        passwdCheck: [{ required: true, validator: validatePassCheck, trigger: 'change' }]
      },
      // 密码黑名单
      pwdBlackList: [],
      showDefaultAvatar:false,
      pass:{
        oldPassType:'password',
        passType:'password',
        checkPassType:'password',
      }
    };
  },
  computed: {
    pageTitle () {
      //当前菜单显示名
      return this.$store.getters.pageTitle;
    },
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
  },
  mounted() {
    this.setStyle();
    window.onresize = () => {
      this.setStyle();
    };
    this.getUserInfo();
    // 查询密码黑名单
    this.queryPwdList();
  },
  methods: {
    setPassType(type){
      this.pass[type] = this.pass[type] === 'password' ? 'text' : 'password'
    },
    setDefAvatar(event) {
      this.showDefaultAvatar = true;
    },
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.contentHei = this.fullHeight - 60 + 'px'; // 80是头部高度  60是上下padding
    },
    // 获取用户信息
    getUserInfo() {
      let _this = this;
      baseInfo()
        .then((res) => {
          if (res.data.code === 1) {
            sessionStorage.removeItem('November');
            let userId = res.data.data.id;
            let nickname = res.data.data.nickname;
            let initPwd = res.data.data.initialPassword;
            let avatar = res.data.data.avatar || '';
            let companyName = res.data.data.companyName;
            let companyId = res.data.data.companyId;
            let userName = res.data.data.username;
            let isRootDesigner;
            if (res.data.data.role && res.data.data.role === 'leader') {
              isRootDesigner = true;
            } else {
              isRootDesigner = false;
            }
            // 用户信息
            this.USER_ID = userId;
            this.nickname = nickname;
            this.avatar = `${avatar}`;
            $('#globalNickName').text(nickname);
            if (avatar && avatar != '') {
              $('#globalAvatar').attr('src', this.avatar);
            } else {
              this.avatar = require('@/assets/globalIcon/defult.jpg');
            }
            this.email = res.data.data.email;
            this.mobile = res.data.data.mobile;
            let November = {
              userId: userId,
              userName: userName,
              nickname: nickname,
              companyName: companyName,
              companyId: companyId,
              initPwd: initPwd,
              avatar: avatar,
              isRootDesigner: isRootDesigner,
              distributed: res.data.data.distributed
            };
            sessionStorage.setItem('November', encryption.SelfUseEncrypt(JSON.stringify(November)));
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });

      this.$store.dispatch('user/getUserInfo')
    },
    // 查询密码黑名单
    queryPwdList() {
      getPwdBlackList()
        .then((res) => {
          if (res.data.code === 1) {
            this.pwdBlackList = res.data.data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 上传头像
    // 上传前
    beforeUpload(file) {
      if (file) {
        this.showProgress = true;
      }
    },
    // 上传动画
    upLoadProgress(event, file, fileList) {
      let percent = event.percent;
      percent = percent.toFixed(1);
      this.progressPercent = parseInt(percent);
    },
    // 上传成功
    upLoadSuccess(response, file, fileList) {
      if (response.code == 1) {
        this.showProgress = false;
        this.progressPercent = 0;
        this.modifuyImg(response.data);
      } else {
        this.$Message.error({
          content: '上传失败！',
          duration: 3
        });
      }
    },
    // 上传失败
    upLoadErr(error, file, fileList) {
      this.showProgress = false;
      this.$Message.error({
        content: '上传失败',
        duration: 3
      });
    },
    // 文件类型错误
    onFormatError(file, fileList) {
      if (file) {
        this.$Message.error({
          content: '上传的文件类型错误！',
          duration: 3
        });
      }
    },
    // 文件过大
    onExceededSize(file, fileList) {
      if (file) {
        this.$Message.error({
          content: '上传文件过大！',
          duration: 3
        });
      }
    },
    // 调用设置头像接口
    modifuyImg(url) {
      let params = {
        avatar: url
      };
      modifyAva(params)
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success({
              content: '修改成功',
              duration: 3
            });
            this.getUserInfo();
          } else {
            this.$Message.error({
              content: '修改失败',
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 修改昵称
    reverseNikeName() {
      this.modalNickName = true;
      this.nickNameForm.newName = '';
      this.handleResetNickname('nickNameForm');
    },
    handleSubmitNickname(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.reNickname();
        } else {
          this.$Message.error('表单输入有误，请检查输入后重新输入！');
        }
      });
    },
    handleResetNickname(name) {
      this.$refs[name].resetFields();
    },
    reNickname() {
      modifyNickname({ nickname: this.nickNameForm.newName })
        .then((res) => {
          if (res.data.code == 1) {
            this.$Message.success({
              content: '修改成功！',
              duration: 3
            });
            this.modalNickName = false;
            this.getUserInfo();
            this.$store.dispatch('user/getUserInfo')
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 邮箱
    reverseEmail() {
      clearInterval(this.setInval);
      this.modalEmail = true;
      this.formValidate.email = '';
      this.formValidate.code = '';
      this.isDisabled = false;
      this.emailValBtn = '获取验证码';
      this.handleResetEmail('formValidate');
    },
    handleSubmitEmail(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.reEmail();
        } else {
          this.$Message.error('请完善信息!');
        }
      });
    },
    handleResetEmail(name) {
      this.$refs[name].resetFields();
    },
    reEmail() {
      let data = {
        email: this.formValidate.email,
        code: this.formValidate.code
      };
      modifyEmail(data)
        .then((res) => {
          if (res.data.code == 1) {
            this.$Message.success({
              content: '邮箱修改成功！',
              duration: 3
            });
            this.modalEmail = false;
            this.getUserInfo();
          } else {
            this.$Message.error(res.data.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    verCodeBtn() {
      if (this.formValidate.email === '') {
        this.$Message.error({
          content: '请填写邮箱！',
          duration: 3
        });
        return false;
      }
      this.isDisabled = true;
      this.emailValBtn = 90;
      this.setInval = setInterval(() => {
        this.emailValBtn--;
        if (this.emailValBtn === 0) {
          this.emailValBtn = '重新获取验证码';
          this.isDisabled = false;
          clearInterval(this.setInval);
        }
      }, 1000);
      let data = {};
      sendCode(this.formValidate.email, data)
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success({
              content: '已发送！',
              duration: 3
            });
          } else {
            this.emailValBtn = '获取验证码';
            this.isDisabled = false;
            clearInterval(this.setInval);
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 修改手机号
    reversePhone() {
      this.modalPhone = true;
      this.phoneForm.mobile = '';
      this.handleResetPhone('phoneForm');
    },
    handleSubmitPhone(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let data = {
            mobile: this.phoneForm.mobile
          };
          this.loadingPhone = true;
          modifyPhone(data)
            .then((res) => {
              if (res.data.code == 1) {
                this.$Message.success({
                  content: '修改成功！',
                  duration: 3
                });
                this.modalPhone = false;
                this.getUserInfo();
              } else {
                this.$Message.error(res.data.message);
              }
              this.loadingPhone = false;
            })
            .catch((err) => {
              this.loadingPhone = false;
              console.log(err);
            });
        } else {
          this.$Message.error('请完善信息!');
        }
      });
    },
    handleResetPhone(name) {
      this.$refs[name].resetFields();
    },
    // 修改密码
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.rePasswd();
        } else {
          this.$Message.error('请完善信息!');
        }
      });
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    rePasswd() {
      let data = {
        newPassword: this.formCustom.passwd,
        oldPassword: this.formCustom.oldPasswd
      };
      modifyPwd(data)
        .then((ress) => {
          
          let res = {data:ress}
          
          if (res.data.code == 1) {
            this.$Message.success({
              content: '密码修改成功,请重新登陆!',
              duration: 3
            });
            setTimeout(() => {
              this.Signout();
            }, 3000);
            this.handleReset('formCustom');
          } else if (res.data.code < 0) {
            this.$Message.error(res.data.message);
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 退出登录
    Signout() {
      logout()
        .then((res) => {
          if (res.data.code === 1) {
            ;
            cookieUse.setCookie('desig-token', '', 0);
            cookieUse.setCookie('Authorization', '', 0);
            sessionStorage.removeItem('November');
            // this.$router.push({
            //   path: '/login'
            // });
            window.openLogin(this.$router)
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 2
            });
          }
        })
        .catch((err) => {
          console.log(err);
          this.$Message.error('服务器连接失败！');
        });
    }
  }
};
</script>
<style scoped>
.page-content {
  background-color: var(--card-body-bgcolor);
  border-radius: 10px;
}
.table-wrap {
  padding: 0 30px;
  height: calc(100% - 94px);
  overflow-x: hidden;
  overflow-y: auto;
}
.img-header {
  display: flex;
  justify-content: space-between;
  padding: 20px 20px 0 20px;
}
.base-style {
  display: flex;
  justify-content: flex-start;
  margin-top: 30px;
  padding-left: 65px;
  align-items: center;
}
.base-style-phone {
  display: flex;
  justify-content: flex-start;
  margin-top: 30px;
  padding-left: 52px;
  align-items: center;
}
/deep/.ivu-avatar .ivu-avatar-string{
  line-height: 100px;
  font-size: 20px;
  left:calc(50% - 10px)!important;
}
.pointer{
  cursor: pointer;
}
</style>
